package com.example.schoolguider.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author wjc
 * @date 2024/7/1 9:26
 */
@Component
public class ImgJsonSerializer extends JsonSerializer<String> {

    @Value("${wjc.resources-url}")
    private String imgDomain;

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null || value.isEmpty()) {
            gen.writeString("");
            return;
        } else if (imgDomain == null || imgDomain.isEmpty()) {
            gen.writeString(value);
            return;
        }
        String[] imgs = value.split(",");
        StringBuilder sb = new StringBuilder();

        for (String img : imgs) {
            // 图片为http协议开头，直接返回
            if (PrincipalUtil.isHttpProtocol(img)) {
                sb.append(img).append(",");
            }
            else {
                sb.append(imgDomain).append(img).append(",");
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        gen.writeString(sb.toString());
    }
}
